/*******************************************************************************
 * This file is part of blueprint4j www.blueprint4j.org.
 * 
 *     blueprint4j is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     blueprint4j is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with blueprint4j. If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package blueprint4j.db;

/**
 * Log.java
 * This class holds connections, if connection is broken then it recreates it
 */

import java.sql.*;
import java.io.*;
import java.util.*;

import blueprint4j.utils.*;

public class TableVersion {

	public static final String TABLE_NAME = "d_tab_version";
	private static boolean table_created = false;

	private static void createTableIfNotExist(DBConnection connection)
	throws SQLException,DataException {
		if (!table_created) {
			// create table if not exists
			Statement statement = connection.createStatement();
			try {
				ResultSet rs = statement.executeQuery("select * from " + TABLE_NAME);
			} catch (SQLException slqe) {
				// create the table
				connection.getDataBaseUtils().createTableVersion(connection);
			} finally {
				statement.close();
			}
		}
	}

	public static long getTableVersion(DBConnection connection,String tablename)
	throws SQLException,DataException {
		createTableIfNotExist(connection);
		Statement statement = null;
		try {
			statement = connection.createStatement();
			ResultSet rs = statement.executeQuery("select version from "+TABLE_NAME+" where name = "+ Entity.asSQL(tablename));
			if (rs.next()) {
				return rs.getLong(1);
			} else {
				connection.execute("insert into " + TABLE_NAME + " (name,version) values ("+
				                   Entity.asSQL(tablename) +",0)");
				return 0;
			}
		} finally {
			statement.close();
		}
	}

	public static void updateTableVersion(DBConnection connection,String tablename,long version)
	throws SQLException,DataException {
		createTableIfNotExist(connection);
		connection.execute("update " + TABLE_NAME + " set version = " +
		                                     version + " where name = " + Entity.asSQL(tablename));
	}
}
